import numpy as np
from prettytable import PrettyTable

# https://www.jianshu.com/p/9ad131856078


# 计算年化利率
def calc_rate(nper, monthly_return, total_principal):
    return np.rate(nper, -monthly_return, total_principal, 0) * 12


# 等额还款
def equal_return_info(rate, nper, total_principal):
    # pmt 计算等额还款时每月还款总金额，包括本金和利息
    monthly_return = np.pmt(rate/12, nper, total_principal)
    table = PrettyTable(["month", "monthly_return", "principal", "interest", "principal_remain"])
    principal_remain = total_principal
    for current_per in range(nper + 1):
        if current_per < 1:
            continue
        # ppmt 计算某一期等额分期的本金偿还金额
        # impt 计算某一期等额分期的利息偿还金额
        current_per_principal = np.ppmt(rate/12, current_per, nper, total_principal)
        principal_remain = round(principal_remain + current_per_principal, 2)
        table.add_row([
            current_per,
            "%.2f" % round(monthly_return - 0, 2),
            "%.2f" % round(current_per_principal, 2),
            "%.2f" % round(monthly_return - current_per_principal, 2),
            "%.2f" % -principal_remain,
                       ])
    table.align = "r"
    # table.align['tax_rate'] = 'c'
    print(table)


total = 5000
month = 12
month_return = 444.005
rate_ali = calc_rate(month, month_return, total)
print('如果借款%d元，每月还 %f 元，分%d期，年利率为: ' % (total, month_return, month), rate_ali)

equal_return_info(rate_ali, month, -total)


